package com.heima.user.service.impl;

//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUserDTO;
import com.heima.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
//import org.springframework.data.querydsl.binding.QuerydslBindings;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author wyq
 */
@Slf4j
@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserService apUserService;
    //登录
    @Override
    public ResponseResult login(ApUserDTO dto) {

        String phone = dto.getPhone();
        String password = dto.getPassword();

        if(StringUtils.isNotEmpty(phone)&&StringUtils.isNotEmpty(password)){
            ApUser user = apUserService.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone,phone));

            if(user==null) {
                ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
                //正向加盐与数据库进行比对
              password=DigestUtils.md5DigestAsHex((password+user.getSalt()).getBytes(StandardCharsets.UTF_8));

              //比对错误,设置token并返回
              if(password!=user.getPassword()){
                  ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
              }

              //生成token
                HashMap<String, Object> map = new HashMap<>();
              map.put("token",AppJwtUtil.getToken(user.getId().longValue()));
              user.setPassword("");
              user.setSalt("");
              map.put("user",user);

              return ResponseResult.okResult(map);


        }else {
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }


    }
}
